package org.zjt.servletdemo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.NamedThreadLocal;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.zjt.servletdemo.domain.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Savepoint;
import java.util.Map;


/**
 * DESC
 *
 * @author
 * @create 2017-08-28 下午3:07
 **/
@Service
public class UserService3 {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /*@Transactional*/
    public void saveUser(User user) throws Exception {
        Connection connection = jdbcTemplate.getDataSource().getConnection();
        connection.setAutoCommit(false);
        // PS: after transaction commit , SAVEPOINT savepoint2 does not exist
        Savepoint savepoint1 = null;
        try {
            //insert 记录
            savepoint1 = connection.setSavepoint("savepoint1");
            PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO user (`name`,`age`) VALUES (?,?)");
            preparedStatement.setString(1, user.getName());
            preparedStatement.setInt(2, user.getAge());
            int update = preparedStatement.executeUpdate();

            //spring中嵌套事务的处理
            Savepoint savepoint2 = null;
            try {
                //update 更新名称为大写
                savepoint2 = connection.setSavepoint("savepoint2");
                preparedStatement = connection.prepareStatement("UPDATE user set name = ? where name = ?");
                preparedStatement.setString(1, user.getName().toUpperCase());
                preparedStatement.setString(2, user.getName());
                update = preparedStatement.executeUpdate();
                int i = 0;
                if (i != 0)
                    throw new SQLException();
            } catch (Exception e) {
                e.printStackTrace();
                connection.rollback(savepoint2);
                throw e;
            } finally {
                connection.releaseSavepoint(savepoint2);
            }

            connection.commit();
            System.out.println("----------commit已经执行----------");
        } catch (Exception e) {
            e.printStackTrace();
            connection.rollback(savepoint1);
        } finally {
            if (connection != null) {
                connection.releaseSavepoint(savepoint1);
                connection.setAutoCommit(true);
                connection.close();
            }
        }
    }
}
